<template>
  <div class="base-info-page">
    <Form ref='prodGroupBasicObj' :model="prodGroupBasicObj" :rules="ruleValidate" :label-width="80">

      <!-- <FormItem label="机构" prop="organ_id">

        <Select v-model="prodGroupBasicObj.organ_id" placeholder="请选择机构">
          <Option v-for="item in organList" :value="item.id" :key="item.id">{{item.name}}</Option>
        </Select>
      </FormItem> -->





      <FormItem label="名称" prop="name">

        <Input v-model="prodGroupBasicObj.name" placeholder="请输入名称"></Input>
      </FormItem>


      <!-- <FormItem label="售课开始时间" prop="sale_start_time">

        <Date-picker type="date" v-model="prodGroupBasicObj.sale_start_at"  @on-change="changeSaleStart" placeholder="选择日期" style="width: 200px"></Date-picker>
      </FormItem>
        <FormItem label="售课结束时间" prop="sale_expire_time">

       <Date-picker type="date"  v-model="prodGroupBasicObj.sale_expire_at" @on-change="changeSaleExpire" placeholder="选择日期" style="width: 200px" ></Date-picker>
      </FormItem> -->
      <FormItem label="简介" prop="remark">
        <Input v-model="prodGroupBasicObj.remark" type="textarea" :rows="3" placeholder="请输入简介"></Input>
      </FormItem>
      <!-- 默认医药类 -->
    <FormItem label="产品类型" prop="shop_type">
        <RadioGroup v-model="prodGroupBasicObj.shop_type">
          <Radio label="1" >医药类</Radio>
          <Radio label="2" >普通商品</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="分类" prop="property_id">
        <!-- 根据选择的产品类型 展示分类 多选  filterable  multiple -->
        <Select v-model="prodGroupBasicObj.property_id" placeholder="请选择课程类型" >
          <Option v-for="item in property" v-if="item.type ==prodGroupBasicObj.shop_type " :value="item.id" :key="item.id">{{item.name}}</Option>
        </Select>
      </FormItem>
      <FormItem label="商品专区" prop="temp_id">
        <!-- 根据选择的产品类型 展示分类 多选  filterable  multiple -->
        <Select v-model="prodGroupBasicObj.temp_id" placeholder="请选择专区" >
          <Option v-for="item in tempList" v-if="item.type ==prodGroupBasicObj.shop_type " :value="item.id" :key="item.id">{{item.name}}</Option>
        </Select>
      </FormItem>
       <FormItem label="所属导航类型" prop="label_id">
        <!-- 根据选择的产品类型 展示分类 多选  filterable  multiple -->
        <Select v-model="prodGroupBasicObj.label_id" placeholder="请选择类型" >
          <Option v-for="item in labelList" v-if="item.type ==prodGroupBasicObj.shop_type " :value="item.id" :key="item.id">{{item.name}}</Option>
        </Select>
      </FormItem>
       <FormItem label="销售状态" prop="sale_estate">
        <RadioGroup v-model="prodGroupBasicObj.sale_estate">
          <Radio label="1" >上架</Radio>
          <Radio label="0" >下架</Radio>
        </RadioGroup>
      </FormItem>
       <FormItem label="首页展示" prop="is_home">
        <RadioGroup v-model="prodGroupBasicObj.is_home">
          <Radio label="1" >是</Radio>
          <Radio label="0" >否</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="热门推荐" prop="is_hot">
        <RadioGroup v-model="prodGroupBasicObj.is_hot">
          <Radio label="1" >是</Radio>
          <Radio label="0" >否</Radio>
        </RadioGroup>
      </FormItem>

      <FormItem label="排序" prop="sorter">

        <Input v-model="prodGroupBasicObj.sorter" placeholder="请输入排序"></Input>
      </FormItem>
       <FormItem label="是否为云仓产品" prop="is_cloudhouse">
        <RadioGroup v-model="prodGroupBasicObj.is_cloudhouse">
          <Radio label="1" >是</Radio>
          <Radio label="0" >否</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="商家" prop="business_id">

        <Select v-model="prodGroupBasicObj.business_id" placeholder="请选择商家">
           <Option value='0' >平台</Option>
          <Option v-for="item in business" :value="item.id" :key="item.id">{{item.company_name}}</Option>
        </Select>
      </FormItem>
       <FormItem label="选择门店" prop="store_id">
      <!-- 注：必须是这对应的类型值  这里数组里的值必须是int ，不能是string -->
      <!-- {{prodGroupBasicObj.store_id}} filterable  multiple-->
        <Select v-model="prodGroupBasicObj.store_id"  placeholder="请选择门店"  >
          <Option  v-for="item in storeList" :value="item.id"  :key="item.id" >{{item.name}}</Option>
        </Select>


      </FormItem>

      <FormItem label="规格" prop="pattern">
        <RadioGroup v-model="prodGroupBasicObj.pattern">
          <Radio :label="item.id" v-for="(item,index) in patternType">{{item.name}}</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="单规格" prop="realname" v-if='prodGroupBasicObj.pattern=="0"'>


        <Table width="1100" border :columns="normsColumns" :data="prodGroupBasicObj.normsValueSingle">
            <template slot-scope="{ row, index }" slot="cover_image">
                <div class="flex-box flex-center flex-margin">
                      <Icon @click="upload('single')" v-if='!row.cover_image' type="md-square-outline" size='36' class='cover-style' />
                      <div v-else>
                        <video @click="upload('single')" v-show="row.cover_image_type==='mp4'" :src="row.cover_image" style="width:52px;height:52px;">
                        </video>
                        <img v-show="row.cover_image_type!=='mp4'" @click="upload('single')"  :src="row.cover_image" style="width: 100%;height:52px;" />
                      </div>

                </div>
            </template>

            <template slot-scope="{ row, index }" slot="name">
                <div class="flex-box flex-center flex-margin">
                  -
                </div>
            </template>

            <template slot-scope="{ row, index }" slot="sku">
                <div class="flex-box flex-center flex-margin">
                    <Input type="textarea"  v-model="prodGroupBasicObj.normsValueSingle[index].sku" placeholder="请输入sku" style="width: 300px"></Input>

                </div>
            </template>

            <template slot-scope="{ row, index }" slot="cost">
                <div class="flex-box flex-center flex-margin">
                     <Input v-model="prodGroupBasicObj.normsValueSingle[index].cost" placeholder="请输入成本价" style="width: 300px"></Input>


                </div>
            </template>

            <template slot-scope="{ row, index }" slot="price">
                <div class="flex-box flex-center flex-margin">
                    <Input v-model="prodGroupBasicObj.normsValueSingle[index].price" placeholder="请输入零售价" style="width: 300px"></Input>


                </div>
            </template>

            <template slot-scope="{ row, index }" slot="course_num">
                <div class="flex-box flex-center flex-margin">
                        <Input v-model="prodGroupBasicObj.normsValueSingle[index].course_num" placeholder="请输入课时" style="width: 300px"></Input>


                </div>
            </template>
             <template slot-scope="{ row, index }" slot="sorter">
                <div class="flex-box flex-center flex-margin">
                         <Input v-model="prodGroupBasicObj.normsValueSingle[index].sorter" placeholder="请输入排序" style="width: 300px"></Input>


                </div>
            </template>
            <template slot-scope="{ row, index }" slot="use_day">
                <div class="flex-box flex-center flex-margin">
                         <Input v-model="prodGroupBasicObj.normsValueSingle[index].use_day" placeholder="请输入有效天数" style="width: 300px"></Input>


                </div>
            </template>
            <!-- <template slot-scope="{ row, index }" slot="use_time">
                <div class="flex-box flex-center flex-margin">
                    <Date-picker type="daterange" :options="useTimeOptions" @on-change='setUseTime($event,index)' @on-clear='clearUseTime(index)'  format="yyyy-MM-dd" placement="top" placeholder="选择日期"  style="width: 200px;"></Date-picker>




                </div>
            </template> -->

             <template slot-scope="{ row, index }" slot="virtual_sale_count">
                <div class="flex-box flex-center flex-margin">

                   <Input v-model="prodGroupBasicObj.normsValueSingle[index].virtual_sale_count" placeholder="请输入虚拟销量" style="width: 300px"></Input>

                </div>
            </template>
             <template slot-scope="{ row, index }" slot="number">
                <div class="flex-box flex-center flex-margin">
                        <Input v-model="prodGroupBasicObj.normsValueSingle[index].number" placeholder="请输入库存" style="width: 300px"></Input>


                </div>
            </template>
        </Table>
      </FormItem>


      <FormItem v-if='prodGroupBasicObj.pattern=="1"' label="规格模板" prop="realname">
        <Button type="primary" icon="ios-search" @click="setNorms">立即设置</Button>
      </FormItem>
      <!-- 批量设置多规格 -->
      <FormItem label="批量设置"  v-if='prodGroupBasicObj.pattern=="1" && prodGroupBasicObj.normsValue.length'>
         <Table width="1100" border :columns="normsColumns" :data="normsValueList">
            <template slot-scope="{ row, index }" slot="cover_image">
                <div class="flex-box flex-center flex-margin">
                      <Icon @click="upload('multipleAction')" v-if='!row.cover_image' type="md-square-outline" size='36' class='cover-style' />
                      <div v-else>
                        <video @click="upload('multipleAction')" v-show="row.cover_image_type==='mp4'" :src="row.cover_image" style="width:52px;height:52px;">
                        </video>
                        <img v-show="row.cover_image_type!=='mp4'" @click="upload('multipleAction')"  :src="row.cover_image" style="width:52px;height:52px;padding:5px;" />
                      </div>

                </div>
            </template>

            <template slot-scope="{ row, index }" slot="name">
                <div class="flex-box flex-center flex-margin">
                  -
                </div>
            </template>

            <template slot-scope="{ row, index }" slot="sku">
                <div class="flex-box flex-center flex-margin">
                    <Input type="textarea"  v-model="normsValueList[index].sku" @on-change='setNormsValue("sku",normsValueList[index].sku)' placeholder="请输入sku" style="width: 300px"></Input>

                </div>
            </template>

            <template slot-scope="{ row, index }" slot="cost">
                <div class="flex-box flex-center flex-margin">
                     <Input v-model="normsValueList[index].cost" @on-change='setNormsValue("cost",normsValueList[index].cost)' placeholder="请输入成本价" style="width: 300px"></Input>


                </div>
            </template>

            <template slot-scope="{ row, index }" slot="price">
                <div class="flex-box flex-center flex-margin">
                    <Input v-model="normsValueList[index].price" @on-change='setNormsValue("price",normsValueList[index].price)'  placeholder="请输入零售价" style="width: 300px"></Input>


                </div>
            </template>

           <!--  <template slot-scope="{ row, index }" slot="course_num">
                <div class="flex-box flex-center flex-margin">
                        <Input v-model="normsValueList[index].course_num" @on-change='setNormsValue("course_num",normsValueList[index].course_num)' placeholder="请输入课时" style="width: 300px"></Input>


                </div>
            </template> -->
            <!--  <template slot-scope="{ row, index }" slot="sorter">
                <div class="flex-box flex-center flex-margin">
                         <Input v-model="normsValueList[index].sorter" @on-change='setNormsValue("sorter",normsValueList[index].sorter)' placeholder="请输入排序" style="width: 300px"></Input>


                </div>
            </template> -->
            <!-- <template slot-scope="{ row, index }" slot="use_time">
                <div class="flex-box flex-center flex-margin">
                    <Date-picker type="daterange" :options="useTimeOptions" @on-change='setNormsValue("set_time",$event)' @on-clear='setNormsValue("clear_time",$event)'  format="yyyy-MM-dd" placement="top" placeholder="选择日期"  style="width: 200px;"></Date-picker>

                </div>
            </template> -->
              <!-- <template slot-scope="{ row, index }" slot="use_day">
                <div class="flex-box flex-center flex-margin">
                     <Input v-model="normsValueList[index].use_day" @on-change='setNormsValue("use_day",normsValueList[index].use_day)' placeholder="请输入有效天数" style="width: 300px"></Input>


                </div>
            </template> -->

             <template slot-scope="{ row, index }" slot="virtual_sale_count">
                <div class="flex-box flex-center flex-margin">

                   <Input v-model="normsValueList[index].virtual_sale_count" @on-change='setNormsValue("virtual_sale_count",normsValueList[index].virtual_sale_count)' placeholder="请输入虚拟销量" style="width: 300px"></Input>

                </div>
            </template>
             <template slot-scope="{ row, index }" slot="number">
                <div class="flex-box flex-center flex-margin">

                   <Input v-model="normsValueList[index].number" @on-change='setNormsValue("number",normsValueList[index].number)' placeholder="请输入库存" style="width: 300px"></Input>

                </div>
            </template>
            <template slot-scope="{ row, index }" slot="sorter">
                <div class="flex-box flex-center flex-margin">

                   <Input v-model="normsValueList[index].sorter" @on-change='setNormsValue("number",normsValueList[index].sorter)' placeholder="请输入排序" style="width: 300px"></Input>

                </div>
            </template>
        </Table>


      </FormItem>
      <!-- 批量end -->
      <!-- 多规格数据 -->
      <FormItem label="" prop="realname" v-if='prodGroupBasicObj.pattern=="1" && prodGroupBasicObj.normsValue.length'>
       <Table width="1100" border :columns="normsColumns" :data="prodGroupBasicObj.normsValue">
            <template slot-scope="{ row, index }" slot="cover_image">
                <div class="flex-box flex-center flex-margin">
                      <Icon @click="upload('multiple',index)" v-if='!row.cover_image' type="md-square-outline" size='36' class='cover-style' />
                      <div v-else>
                        <video @click="upload('multiple',index)" v-show="row.cover_image_type==='mp4'" :src="row.cover_image" style="width:52px;height:52px;">
                        </video>
                        <img v-show="row.cover_image_type!=='mp4'" @click="upload('multiple',index)"  :src="row.cover_image" style="width:52px;height:52px;padding:5px;" />
                      </div>

                </div>
            </template>

            <template slot-scope="{ row, index }" slot="name">
                <div class="flex-box flex-center flex-margin">
                  {{row.name}}
                </div>
            </template>

            <template slot-scope="{ row, index }" slot="sku">
                <div class="flex-box flex-center flex-margin">
                    <Input type="textarea"  v-model="prodGroupBasicObj.normsValue[index].sku"  placeholder="请输入sku" style="width: 300px"></Input>

                </div>
            </template>

            <template slot-scope="{ row, index }" slot="cost">
                <div class="flex-box flex-center flex-margin">
                     <Input v-model="prodGroupBasicObj.normsValue[index].cost"  placeholder="请输入成本价" style="width: 300px"></Input>


                </div>
            </template>

            <template slot-scope="{ row, index }" slot="price">
                <div class="flex-box flex-center flex-margin">
                    <Input v-model="prodGroupBasicObj.normsValue[index].price" placeholder="请输入零售价" style="width: 300px"></Input>


                </div>
            </template>

            <template slot-scope="{ row, index }" slot="course_num">
                <div class="flex-box flex-center flex-margin">
                        <Input v-model="prodGroupBasicObj.normsValue[index].course_num" placeholder="请输入课时" style="width: 300px"></Input>


                </div>
            </template>
             <template slot-scope="{ row, index }" slot="number">
                <div class="flex-box flex-center flex-margin">
                        <Input v-model="prodGroupBasicObj.normsValue[index].number" placeholder="请输入库存" style="width: 300px"></Input>


                </div>
            </template>
             <template slot-scope="{ row, index }" slot="sorter">
                <div class="flex-box flex-center flex-margin">
                         <Input v-model="prodGroupBasicObj.normsValue[index].sorter" placeholder="请输入排序" style="width: 300px"></Input>


                </div>
            </template>
             <template slot-scope="{ row, index }" slot="use_day">
                <div class="flex-box flex-center flex-margin">
                     <Input v-model="prodGroupBasicObj.normsValue[index].use_day"  placeholder="请输入成本价" style="width: 300px"></Input>


                </div>
            </template>

             <template slot-scope="{ row, index }" slot="virtual_sale_count">
                <div class="flex-box flex-center flex-margin">

                   <Input v-model="prodGroupBasicObj.normsValue[index].virtual_sale_count" placeholder="请输入虚拟销量" style="width: 300px"></Input>

                </div>
            </template>
        </Table>

      </FormItem>
      <FormItem label="封面" prop="realname">
        <Button type="primary" icon="ios-search" @click="upload('cover')">上传图片</Button>
      </FormItem>
      <FormItem>
        <img v-if="prodGroupBasicObj.cover_image && prodGroupBasicObj.cover_image_type!='mp4'" :src="prodGroupBasicObj.cover_image"
          style="width: 70px;height: 70px;border: 1px solid #eeeeee;" />
        <video v-if="prodGroupBasicObj.cover_image && prodGroupBasicObj.cover_image_type=='mp4'" :src="prodGroupBasicObj.cover_image"
          style="width: 70px;height: 70px;border: 1px solid #eeeeee;">
        </video>
      </FormItem>


      <FormItem label="相册" prop="realname">
        <Button type="primary" icon="ios-search" @click="upload('album')">上传图片</Button>
      </FormItem>
      <FormItem v-if="prodGroupBasicObj.album_imageArr && prodGroupBasicObj.album_imageArr.length">
        <div v-for="(item,index) in prodGroupBasicObj.album_imageArr" style="display: inline-block;margin-right: 10px;margin-bottom: 10px;">
          <video v-if="item.extension=='mp4'" :src="item.url" style="width: 70px;height: 70px;border: 1px solid #eeeeee;"></video>
          <img v-else :src="item.url" style="width: 70px;height: 70px;border: 1px solid #eeeeee;" />
        </div>

      </FormItem>
    </Form>


    <Modal v-model="uploadModal" title="图片管理" class="uploadModal-wrap" :closable='isClosable'>
      <!-- 上传组件 -->
      <div>
        <UploadTool :showUpload='showUpload' :optionObj='uploadImgPathList' @getSelectedImgList='getSelectedImgList'></UploadTool>
      </div>
      <div slot="footer">
        <Button @click='cancelUploadModal'>取消</Button>
        <Button type="primary" @click='confirm(uploadType)'>确定</Button>
      </div>

    </Modal>
    <!-- 多规格弹窗 -->
    <Modal v-model="normsModal" title="设置产品规格">
      <Tabs value="name1" v-model='currentTabPane' class='normsModal'>
        <TabPane label="基础信息" name="name1">
          <Form ref="normsValidate" :model="normsForm" :rules="normsRuleValidate" :label-width="80">
            <FormItem label="规格模板" prop="code">
              <Select v-model="normsTemplateId" placeholder="请选择规格模板">
                <Option v-for="item in data.normsTemplate" :value="item.id" :key="item.id">{{item.name}}</Option>
              </Select>
            </FormItem>
            <FormItem label="规格名" prop="code">
              <CheckboxGroup v-model="normsNamesGroup" @on-change='changeNormsName'>
                <Checkbox :label="item.id" v-for="(item,index) in normsName">{{item.name}}</Checkbox>
              </CheckboxGroup>
            </FormItem>
            <!--  -->
            <div v-for="(item,index) in normsName">
              <FormItem v-if="normsNamesGroup.includes(item.id)" :label="item.name" prop="code">
                <CheckboxGroup v-model="item.itemGroup">
                  <Checkbox :label="row.id" v-for="(row,index) in item.sub">{{row.name}}</Checkbox>
                </CheckboxGroup>
              </FormItem>
            </div>
          </Form>
        </TabPane>
        <TabPane label="自定义规格模板" name="name2">
          <BaseInfo></BaseInfo>

        </TabPane>

      </Tabs>


      <div slot="footer">
        <div v-if="currentTabPane=='name1'">
          <Button @click='normsModal=false'>取消</Button>
          <Button type="primary" @click="saveNorms">确定</Button>
        </div>
        <div v-else>
          <Button @click='normsModal=false'>取消</Button>
          <Button type="primary" @click="saveSelfNorms">确定</Button>
        </div>
      </div>

    </Modal>


    <!-- 删除弹窗 -->
    <Modal style='display: none;' v-model="delModal9999" title="提示">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定要删除吗？</p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>

    <!-- 标库弹窗 -->
    <Modal v-model="productLibraryModal" :closable="false" :width="1000">
      <div class="p-relative">

        <div class="flex-box search-area">
          <div class="flex-item">
            <Select filterable v-model="searchObj.property_id" placeholder="请选择产品分类">
              <Option :value="item.id" v-for="(item,index) in library.propertyList">{{item.name}}</Option>
            </Select>
          </div>

          <div class="flex-item">
            <Input v-model="searchObj.name" placeholder="请输入要搜索的产品名称"></Input>
          </div>
          <div class="flex-item search-btn" @click="searchLibrary">
            <Button type="primary">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="resetLibrary">
            <Button>重置</Button>
          </div>

        </div>
      </div>

      <Table border :columns="libraryColumns" :data="library.list" border :no-data-text="loadingText ? loadingText : '暂无数据'"
        border ref="tables" editable search-place="top">
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='primary' @click="selectRow(row, index)" size='small'>选择</Button>
          </div>
        </template>
      </Table>
      <!-- <i-table highlight-row @on-current-change="changeRow" border :columns="library.columns" :data="library.list"></i-table> -->
      <Page class="foot-page" :current='library.current' :total="library.total" :page-size="library.pageSize"
        show-total show-elevator @on-change="libraryListPage"></Page>
      <div slot="footer">
        <Button @click='productLibraryModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>

    <!--  -->
  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import {
    getnormstemplateformat,
    getLibraryList,
    downImg,
    addView
  } from '@/api/product-group/course-product-list'
  import {

    add //商品规格模板页面的年增接口


  } from '@/api/product-group/product-normstemplate'
  import BaseInfo from '../product-normstemplate/base-info/base-info.vue'
  import Tables from '_c/tables'
  // 上传组件
  import UploadTool from '../../../components/uploadTool/uploadTool.vue'
  import {uploadImgPathList} from '@/config/global.js'



  export default {
    name: 'tables_page',
    components: {
      Tables,
      UploadTool, //注册上传组件
      BaseInfo
    },
    created() {
      // 新增
      // if(this.isAdd){
      //   this.addView()
      // }else{

      // }


    },
    watch: {
      uploadModal(newVal) {
        if (!newVal) {
          this.showUpload = false; //关闭弹窗，showUpload设置为false
        }
      },
      normsTemplateId(newVal, oldVal) {
        if (newVal) {
          this.getnormstemplateformat(newVal) //template_norms_id

        }
      },

    },
    mounted() {
      // this.uploadList = this.$refs.upload.fileList;

    },
    props: ['property', 'isAdd','storeList','business','courseProperty','organList','tempList','labelList'],
    computed: {
      ...mapState({
        prodGroupBasicObj: state => state.share.prodGroupBasicObj,
        productNormstemplateObj: state => state.share.productNormstemplateObj, //商品规格模板页面，搬过来
      }),
    },
    data() {
      return {
        // 子组件传递过来
         isClosable:false,
        fromChild: {
          selectedImgList: []
        },
        uploadType: '', //上传按钮判断
        uploadIndex:0,
        // 批量设置多规格
        normsValueList:[{
            cover_image: '', // 封面
            sku:'',
            name: '', // 规格名称
            price: 0, // 周期价格
            cost: 0, // 成本
            number: 0, // 库存
            src: '',
            norms_ids: 0,
            sorter:0,
            virtual_sale_count:0,
            start_time:'',
            end_time:'',
            use_day:0,
        }],
        // 标库
        loadingText: '',
        searchObj: {

        },
        data: {
          singleNorm: [{
            cover_image: '', // 封面
            sku:'',
            name: '', // 规格名称
            price: 0, // 周期价格格
            cost: 0, // 成本
            number: 0, // 库存
            src: '',
            norms_ids: 0,
            sorter:0,
            virtual_sale_count:0,
            start_time:'',
            end_time:''
          }],
          manyNorm: [],

          businessList:[],//商家下拉
          normsTemplate: [],
          photo_album_list: [], //相册
          uploadparams: {
            name: '1.png',
            dirType: 0,
            saveType: 0,
            userType: 0,
            sourceType: 0
          }
        },
        productLibraryModal: false, //产品标库
        libraryColumns: [{
            title: 'ID',
            key: 'id',
            width: '70'
          },
          {
            title: '分类',
            key: 'property_name'
          },
          {
            title: '条形码',
            key: 'shape_code'
          },
          {
            title: '产品名称',
            key: 'name'
          },
          {
            title: '生产厂家',
            key: 'factory'
          },
          {
            title: '操作',
            slot: 'action',
            width: 150,
            align: 'center',

          }
        ],
        library: {

          list: [], //列表数据
          total: 0,
          pageSize: 10,
          current: 1,
          propertyList: [], //分类列表
          property_id: '', //分类id
          name: '', //搜索名称
          changeRow: [] //选中当前行数据
        },
        // 标库end
        normsTemplateFromFather: [],
        currentTabPane: 'name1',
        normsNamesGroup: [],
        itemGroup: [],
        normsName: [],
        normsTemplateId: '',
        normsForm: {},
        normsValidate: {},
        normsRuleValidate: {},

        normsModal: false,
        delModal9999: false,
        // 上传
        showUpload: false, //父组件中点击上传按钮，子组件上传弹窗显示，props
        delModal: false,
        patternType: [{
            name: '单规格',
            id: 0
          },
          {
            name: '多规格',
            id: 1
          }
        ],

        uploadImgPathList:uploadImgPathList,
        // 分页
        page: {
          pageSize: 10,
          current: 1,
          total: 0
        },
        // 分页end
        searchDirType: '', //
        indexArr: [],
        selectImgList: [],
        selectCurrent: null,
        fileCurrent: null,
        current: null,

        uploadList: [], //

        defaultList: [],
        uploadModal: false,

        // 上传end
        formValidate: {},
        tableData: [],
        ruleValidate: {
          // business_id: [{
          //   required: true,
          //   type:'number',
          //   message: '请选择商家',
          //   trigger: 'change'
          // }],
          organ_id: [{
            required: true,
            type:'number',
            message: '请选择机构',
            trigger: 'change'
          }],
           course_property_id: [{
            required: true,
            type:'number',
            message: '请选择课程类型',
            trigger: 'change'
          }],
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],

          property_id: [{
            required: true,
            type:'number',
            message: '请选择产品类型',
            trigger: 'change'
          }],
          store_id: [{
            required: true,
            type: 'number',
            message: '请选择门店',
            trigger: 'change'
          }]
        },
        useTime:[],
        normsColumns: [
          {
            title: '封面',
            slot: 'cover_image',
            fixed: 'left',
             width: 150,
          },
          {
            title: '规格名称',
            width: 100,
            slot: 'name',
            fixed: 'left'
          },
          {
            title: 'sku',
            slot: 'sku',
            width: 200
          },

          {
            title: '零售价',
            slot: 'cost'
          },
          {
            title: '优惠价',
            slot: 'price'
          },
          // {
          //   title: '课时',
          //   slot: 'course_num'
          // },
          //  {
          //   title: '有效天数',
          //   slot: 'use_day',
          //    width: 220
          // },
          // {
          //   title: '有效时间',
          //   slot: 'use_time',
          //    width: 220
          // },
          {
            title: '虚拟销量',
            slot: 'virtual_sale_count'
          },
          {
            title: '库存',
            slot: 'number',
             width: 220
          },
          {
            title: '排序',
            slot: 'sorter'
          }



        ],
        //时间限制
        useTimeOptions:{
          disabledDate (date) {
              return date && date.valueOf() < Date.now() - 86400000;
          }
      },
        normsColumnsData:[{}],
        editIndex: 0, // 当前聚焦的输入框的行数
        editName: '', // 第一列输入框，当然聚焦的输入框的输入内容，与 data 分离避免重构的闪烁
        editAge: '', // 第二列输入框
        editBirthday: '', // 第三列输入框
        editAddress: '', // 第四列输入框
      }
    },
    methods: {
      ...mapMutations([
        'setProdGroupGoodsDetailObj', //宝贝详情
        'setProdGroupBasicObj',
        'setProdGroupNormsValue', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
        'setProdGroupNormsValueSingle',
        'setProductNormstemplateObj',
        'setProdGroupNorms'
      ]),
      // 校验数据
      async validateForm () {
        let flag = null;
        let isVaild=await this.$refs['prodGroupBasicObj'].validate(valid => {
          if (valid) {
            flag=true
          } else {
           flag=false
          }
        })
        return isVaild
      },

      //修改的时候显示单规格，多规格
      init() {
        // let singleNorm = [{
        //     cover_image: '', // 封面
        //     sku:'',
        //     name: '', // 规格名称
        //     price: 0, // 周期价格
        //     cost: 0, // 成本
        //     number: 0, // 库存
        //     src: '',
        //     norms_ids: 0,
        //     sorter:0,
        //     virtual_sale_count:0,
        //     start_time:'',
        //     end_time:'',
        //     use_time:[],
        //     use_day:0,
        // }];
        if (this.prodGroupBasicObj.pattern == 0) {
          this.data.singleNorm = this.prodGroupBasicObj.normsValue

        } else {
          this.data.manyNorm = this.prodGroupBasicObj.normsValue
        }


      },
      getSelectedImgList(e) {
        this.fromChild.selectedImgList = e;



      },
      searchLibrary(){
        this.showProductLibrary()
      },
      resetLibrary(){
        this.searchObj = {} //清空搜索框
        this.showProductLibrary();
      },
      libraryListPage(e) {
        this.library.current = e;
        this.showProductLibrary()

      },
      showProductLibrary() {
        let _this = this;

        this.productLibraryModal = true
        let params = {
          page: this.library.current,
          property_id: this.searchObj.property_id,
          name: this.searchObj.name
        };

        getLibraryList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;
            _this.library.list = result.list;
            _this.library.propertyList = result.property;
            _this.library.total = result.total;


          } else {
            //axios响应拦截
          }

        }).catch(function(error) {
          //异常
          _this.createModal = false;
          console.log(error)
        })

      },
      selectRow(row) {
        // 此方法填充名称，封面，相册，宝贝详情

        let _this = this;
        this.productLibraryModal = false;
        this.setProdGroupGoodsDetailObj(row.description);
        let params = {

          cover_image: row.cover_image,
          album_image: row.album_image,

        }

        downImg(params).then(res => {
          if (res.data.status == 1) {

            let result = res.data.data;

            let obj = {
              name: row.name,

              cover_image: result[0][0].src,
              pattern: _this.prodGroupBasicObj.pattern,
              normsValue: _this.prodGroupBasicObj.normsValue
            }
            _this.setProdGroupBasicObj(obj);


            // _this.data.list=result;

            //_this.$Message.success('操作成功')



          } else {

          }

        }).catch(function(error) {
          //异常
          console.log(error)
        })


      },
      changeRow(currentRow, oldCurrentRow) {
        this.$data.library.changeRow = currentRow;
      },

      saveSelfNorms() {

        let _this = this;
        if (!this.productNormstemplateObj.name) {
          this.$Message.error('请输入模板名称')
          return
        }
        if (!this.productNormstemplateObj.template_norms_property_id) {
          this.$Message.error('请选择顶级规格分类')
          return
        }
        if (!this.productNormstemplateObj.norms) {
          this.$Message.error('请选择规格')
          return
        }

        let basicObj = {
          id: _this.rowId, //修改时候，模板id
          is_norms: this.productNormstemplateObj.is_norms,
          name: this.productNormstemplateObj.name, //模板名称
          template_norms_property_id: this.productNormstemplateObj.template_norms_property_id //顶级规格分类id
        }
        let obj = {
          basic: basicObj,
          norms: this.productNormstemplateObj.norms,
          expand: {},
          property: []
        }
        // 新增接口
        add(obj).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;
            _this.data.normsTemplate = result.normsTemplate;
            _this.$Message.success('自定义模板添加成功');
            _this.setProductNormstemplateObj({})
            _this.currentTabPane = 'name1'
          } else {
            //axios响应拦截
          }
        }).catch(function(error) {
          //异常
          _this.createModal = false;
          console.log(error)
        })

      },
      addView() {
        let _this = this;
        //新增的时候用于获取下拉框分类数据
        addView().then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;
            _this.$nextTick(function(cv) {
              _this.data.normsTemplate = result.normsTemplate;
              _this.$forceUpdate()
              _this.data.businessList=result.business
            })


            //_this.$Message.success('操作成功');

          } else {

            //axios响应拦截
          }

        }).catch(function(error) {
          //异常

          console.log(error)
        })

      },
      changeSaleStart(e){
        console.log(e)
          this.prodGroupBasicObj.sale_start_at =e
      },
      changeSaleExpire(e){
        console.log(e)
          this.prodGroupBasicObj.sale_expire_at =e
      },
      changeNormsName() {

      },
      setNorms() {
        let _this = this;
        this.normsModal = true;
        this.$nextTick(function(cv) {
          _this.addView();
          _this.$forceUpdate()
        })

      },
      cartesianProduct(arr) {
        return arr.reduce(function(a, b) {
          return a.map(function(x) {
            return b.map(function(y) {
              return x.concat(y);
            })
          }).reduce(function(a, b) {
            return a.concat(b)
          }, [])
        }, [
          []
        ])
      },
      saveNorms() {
        // console.log(this.normsName)
        // console.log(this.normsNamesGroup)
        let _this=this;
        // 判断比选项目
        if(!this.normsTemplateId){
          this.$Message.error('请选择规格模板')
          return
        }
        if(!this.normsNamesGroup.length){
          this.$Message.error('请选择规格属性')
          return
        }
        this.prodGroupBasicObj.template_norms_id = this.normsTemplateId
        console.log('*****',this.prodGroupBasicObj.template_norms_id )
        let isChild=true;

        this.normsName.forEach(function(item,i){
          if(_this.normsNamesGroup.includes(item.id) && item.itemGroup.length<=0){
            isChild=false;
          }
          return

        })
        if(!isChild){
          this.$Message.error('请选择规格属性')
          return
        }

        let itemGroupTrueList = [];
        itemGroupTrueList = this.normsName.filter((row => {
          return row.itemGroup.length
        }))
        let newList = [];

        itemGroupTrueList.forEach(function(cv) {
          let checkedSub = []
          let list = cv.itemGroup;
          // 返回选中的sub
          checkedSub = cv.sub.filter(function(row) {
            return list.indexOf(row.id) >= 0
          })
          let obj = {
            name: cv.name,
            sub: checkedSub
          }
          newList.push(obj)

        })
        let last = []
        // console.log('*****',newList)

        newList.forEach(function(item) {

          let list = item.sub.map(function(row) {
            return {
              title: item.name,
              name: row.name,
              filterName: item.name + ':' + row.name,
              id: row.id
            }

          })
          last.push(list)
        })
        let cartesianList = this.cartesianProduct(last); //转成笛卡尔积
        let normsList = cartesianList.map(function(item) {
          let normsName = [];
          let normsId = [];
          normsName = item.map(function(row) {
            return row.filterName
          })
          normsId = item.map(function(row) {
            return row.id
          })

          return {
            name: normsName.join(','),
            norms_ids: normsId.join('_'),
            // 输入的
            cover_image: '', // 封面
            sku:'',
            price: 0, // 周期价格
            cost: 0, // 成本
            number: 0, // 库存
            src: '',
            sorter:0,
            virtual_sale_count:0,
            start_time:'',
            end_time:'',
            use_time:[]
          }

        })
        // return
        // let arr = [{
        //   name: '', //规格名称
        //   norms_ids: 0,
        //    cover_image: '', // 封面
        //     sku:'sdfsdfsdf8974984654',
        //     price: 0, // 周期价格
        //     cost: 0, // 成本
        //     number: 0, // 库存
        //     src: '',
        //     sorter:0,
        //     virtual_sale_count:0,
        //     start_time:'',
        //     end_time:''

        // }]

        this.data.manyNorm = normsList;
        this.setProdGroupNormsValue(this.data.manyNorm)
        this.normsModal = false;
        // this.
        //setProdGroupBasicObj
      },
      getnormstemplateformat(id) {
        let _this = this;
        let params = {
          template_norms_id: id
        }
        getnormstemplateformat(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data;
            result.normsTemplateFormat.forEach(function(cv) {
              cv.itemGroup = []
            })
            _this.normsName = result.normsTemplateFormat;


          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)

          }

        }).catch(function(error) {
          //异常
          console.log(error)
        })




      },

      //上传
      upload(type,index) {
        // type为上传的类型，‘cover’封面
        this.uploadType = type;
        this.uploadIndex = index;
        this.uploadModal = true;
        this.showUpload = true;


      },
      cancelUploadModal() {
        this.uploadModal = false;
        this.showUpload = false;
      },
      delImg(row, index) {
        this.delModal = true;

      },
      confirmDel() {

      },
      remove(row, index) {
        console.log(row)
      },
      upMove(row, index) {},
      downMove(row, index) {},
      confirm(type) {
       let _this=this;
        if (!this.fromChild.selectedImgList.length) {
          this.$Message.error('请选择图片或者视频!');
          return
        }
        this.uploadModal = false;
        //this.fromChild.selectedImgList
        if (type == 'cover') {
          // 封面
          let obj = this.prodGroupBasicObj;
          obj.cover_image = this.fromChild.selectedImgList[0].url;
          obj.cover_image_type = this.fromChild.selectedImgList[0].extension;
          obj.cover_image_file_name = this.fromChild.selectedImgList[0].path_name;
          this.setProdGroupBasicObj(obj)
        } else if (type == 'album') {
          // 相册
          let obj = this.prodGroupBasicObj;
          obj.album_imageArr = this.fromChild.selectedImgList.map((res => {
            return {
              url: res.url,
              extension: res.extension,
              file_name: res.path_name
            }
          }))
        } else if (type == 'single') {
          // 单规格上传

          let obj = this.prodGroupBasicObj.normsValueSingle[0];
          obj.cover_image = this.fromChild.selectedImgList[0].url;
          obj.cover_image_type = this.fromChild.selectedImgList[0].extension;
          obj.cover_image_file_name = this.fromChild.selectedImgList[0].path_name;
          this.data.singleNorm = [obj];
          this.setProdGroupNormsValueSingle(this.data.singleNorm)

        }else if(type=='multiple'){
          // 多规格

          let arr=_this.prodGroupBasicObj.normsValue;
          arr[this.uploadIndex].cover_image = this.fromChild.selectedImgList[0].url || '';
          arr[this.uploadIndex].cover_image_type = this.fromChild.selectedImgList[0].extension || '';
          arr[this.uploadIndex].cover_image_file_name = this.fromChild.selectedImgList[0].path_name || '';
          this.data.manyNorm =JSON.parse(JSON.stringify(arr));
          this.setProdGroupNormsValue(this.data.manyNorm)
        }else if(type=='multipleAction'){
          console.log(this.fromChild.selectedImgList[0].extension)
          // 批量设置多规格
          let obj=this.normsValueList[0];
          this.normsValueList[0].cover_image= _this.fromChild.selectedImgList[0].url;
          this.normsValueList[0].cover_image_type=_this.fromChild.selectedImgList[0].extension;
          let newList=JSON.parse(JSON.stringify(this.prodGroupBasicObj.normsValue));
          newList.forEach(function(cv){
            cv.cover_image = _this.fromChild.selectedImgList[0].url;
            cv.cover_image_type= _this.fromChild.selectedImgList[0].extension;
            cv.cover_image_file_name = _this.fromChild.selectedImgList[0].path_name;
          })
          _this.setProdGroupNormsValue(newList)


        }

      },
      // 批量设置多规格,图片另外设置confirm
      setNormsValue(type,val){

        let newList=JSON.parse(JSON.stringify(this.prodGroupBasicObj.normsValue));
        newList.forEach(function(cv){
          if(type=='set_time')
          {
            cv['start_time']= val[0]
            cv['end_time']= val[1]
            cv['use_time']= val
          }else if(type=='clear_time'){
            cv['start_time']= ''
            cv['end_time']= ''
            cv['use_time']= []

          }else{
            cv[type]=val
          }


        })

        this.setProdGroupNormsValue(newList)

      },
      selectImg(row, index) {

        //this.indexArr用来记录选中图片的索引，判断打勾
        let arrIndex = this.indexArr.indexOf(index); //数组中是否已经存在
        if (arrIndex > -1) {
          // 存在，点击的时候就删除
          this.indexArr.splice(arrIndex, 1);
          this.selectImgList.splice(arrIndex, 1);
        } else {
          // 不存在点击就添加
          this.indexArr.push(index); //索引
          this.selectImgList.push(row); //图片整条数据

        }


      },
      mouseleave(event, row, index) {
        this.current = null;
      },
      mouseenter(event, row, index) {
        this.current = index;
      },
      fileLeave(event, row, index) {
        this.fileCurrent = null;
      },
      fileEnter(event, row, index) {

        this.fileCurrent = index;
      },
      handleView(name) {
        this.imgName = name;
        this.visible = true;
      },
      handleRemove(file) {
        const fileList = this.$refs.upload.fileList;
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
      },
      handleSuccess(res, file) {
        file.url = 'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar';
        file.name = '7eb99afb9d5f317c912f08b5212fd69a';
        console.log(res);
        console.log(file)
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: 'The file format is incorrect',
          desc: 'File format of ' + file.name + '文件格式不正确，请上传格式为png,jpg,jpeg的图片'
        });
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: 'Exceeding file size limit',
          desc: 'File  ' + file.name + '太大，请上传小于2M的图片.'
        });
      },
      handleBeforeUpload() {
        const check = this.uploadList.length < 5;
        if (!check) {
          this.$Notice.warning({
            title: '一次最多可以上传五张图片'
          });
        }
        return check;
      },
      // 上传end
      handleEdit(row, index) {
        this.editName = row.name;
        this.editAge = row.age;
        this.editAddress = row.address;
        this.editBirthday = row.birthday;
        this.editIndex = index;
      },
      handleSave(index) {
        this.data[index].name = this.editName;
        this.data[index].age = this.editAge;
        this.data[index].birthday = this.editBirthday;
        this.data[index].address = this.editAddress;
        this.editIndex = -1;
      },
      getBirthday(birthday) {
        const date = new Date(parseInt(birthday));
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${year}-${month}-${day}`;
      },
      change(status) {
        this.$Message.info('开关状态：' + status);
      },
      setUseTime(timeRange,index,model='single'){
        if(model=='single')
        {
          this.prodGroupBasicObj.normsValueSingle[index].start_time =timeRange[0]
          this.prodGroupBasicObj.normsValueSingle[index].end_time =timeRange[1]
        }else{
          this.prodGroupBasicObj.normsValue[index].start_time=timeRange[0]
          this.prodGroupBasicObj.normsValue[index].end_time=timeRange[1]
        }


      },
      clearUseTime(index,model='single'){
        if(model=='single')
        {
          this.prodGroupBasicObj.normsValueSingle[index].start_time =''
          this.prodGroupBasicObj.normsValueSingle[index].end_time =''
        }else{
          this.prodGroupBasicObj.normsValue[index].start_time=''
          this.prodGroupBasicObj.normsValue[index].end_time=''
        }
      }
    },

  }
</script>

<style lang="scss">
  @import "./base-info";
</style>
